#!/bin/bash

set -e

# 加载路径配置
source "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/../config/paths.conf"

CONFIG_FILE="$CONFIG_DIR/oss_config"
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

log() {
    echo -e "${GREEN}[$(date '+%Y-%m-%d %H:%M:%S')]${NC} $1"
}

warn() {
    echo -e "${YELLOW}[警告]${NC} $1"
}

error() {
    echo -e "${RED}[错误]${NC} $1"
}

# 初始化OSS配置文件
init_oss_config() {
    log "初始化OSS配置文件..."
    
    mkdir -p "$CONFIG_DIR"
    
    cat > "$CONFIG_FILE" << 'EOF'
# OSS配置 - 请根据实际情况修改以下配置

# OSS基本信息
OSS_BUCKET="your-bucket-name"
OSS_ENDPOINT="oss-cn-hangzhou.aliyuncs.com"
OSS_PREFIX="traffic-monitor"
OSS_REGION="oss-cn-hangzhou"

# 认证信息 - 从阿里云控制台获取
# 获取地址: https://ram.console.aliyun.com/manage/ak
OSS_ACCESS_KEY_ID="your-access-key-id"
OSS_ACCESS_KEY_SECRET="your-access-key-secret"
OSS_SECURITY_TOKEN=""  # 可选，使用STS临时令牌时填写

# 上传设置
MAX_UPLOAD_RETRY=3
UPLOAD_TIMEOUT=300
COMPRESSION_ENABLED=true
DELETE_AFTER_UPLOAD=false

# 高级设置
MULTIPART_THRESHOLD=100MB
MULTIPART_PART_SIZE=10MB

# 安全提示: 此文件包含敏感信息，请妥善保管
EOF

    # 设置严格的文件权限
    chmod 600 "$CONFIG_FILE"
    log "✓ OSS配置文件已创建: $CONFIG_FILE"
    log "⚠️  请编辑此文件并配置您的OSS认证信息"
}

# 检查并编辑配置
edit_oss_config() {
    if [ ! -f "$CONFIG_FILE" ]; then
        init_oss_config
    fi
    
    log "正在打开OSS配置文件进行编辑..."
    log "请配置以下信息:"
    echo "1. OSS_BUCKET: 您的OSS存储桶名称"
    echo "2. OSS_ENDPOINT: 存储桶所在区域Endpoint"
    echo "3. OSS_ACCESS_KEY_ID: 访问密钥ID"
    echo "4. OSS_ACCESS_KEY_SECRET: 访问密钥Secret"
    echo ""
    
    # 使用默认编辑器
    ${EDITOR:-vi} "$CONFIG_FILE"
    
    # 验证配置格式
    if source "$CONFIG_FILE" 2>/dev/null; then
        log "✓ 配置文件语法正确"
    else
        error "配置文件语法错误，请检查"
        return 1
    fi
}

# 验证OSS配置
validate_oss_config() {
    if [ ! -f "$CONFIG_FILE" ]; then
        error "OSS配置文件不存在"
        return 1
    fi
    
    # 加载配置
    source "$CONFIG_FILE"
    
    local missing_fields=()
    
    # 检查必要字段
    [ -z "$OSS_BUCKET" ] && missing_fields+=("OSS_BUCKET")
    [ -z "$OSS_ENDPOINT" ] && missing_fields+=("OSS_ENDPOINT")
    [ -z "$OSS_ACCESS_KEY_ID" ] && missing_fields+=("OSS_ACCESS_KEY_ID")
    [ -z "$OSS_ACCESS_KEY_SECRET" ] && missing_fields+=("OSS_ACCESS_KEY_SECRET")
    
    if [ ${#missing_fields[@]} -gt 0 ]; then
        error "以下必要字段未配置: ${missing_fields[*]}"
        return 1
    fi
    
    # 检查是否为示例值
    if [ "$OSS_ACCESS_KEY_ID" = "your-access-key-id" ] || \
       [ "$OSS_ACCESS_KEY_SECRET" = "your-access-key-secret" ]; then
        error "请将示例值替换为实际的AccessKey"
        return 1
    fi
    
    log "✓ OSS配置验证通过"
    echo "  Bucket: $OSS_BUCKET"
    echo "  Endpoint: $OSS_ENDPOINT"
    echo "  AccessKey ID: ${OSS_ACCESS_KEY_ID:0:8}****"
    return 0
}

# 测试OSS连接
test_oss_connection() {
    if ! validate_oss_config; then
        return 1
    fi
    
    log "测试OSS连接..."
    
    # 加载配置
    source "$CONFIG_FILE"
    
    # 创建测试文件
    local test_file="/tmp/oss_test_$(date +%s).txt"
    echo "OSS connection test - $(date)" > "$test_file"
    
    # 使用ossutil测试（如果已安装）
    if command -v ossutil &> /dev/null; then
        log "使用ossutil测试上传..."
        
        # 构建命令基础部分
        local ossutil_cmd="ossutil cp '$test_file' 'oss://$OSS_BUCKET/test/' \
           -e '$OSS_ENDPOINT' \
           -i '$OSS_ACCESS_KEY_ID' \
           -k '$OSS_ACCESS_KEY_SECRET'"
        
        # 只有在有安全令牌时才添加 --sts-token 参数
        if [ -n "$OSS_SECURITY_TOKEN" ]; then
            ossutil_cmd="$ossutil_cmd --sts-token '$OSS_SECURITY_TOKEN'"
        fi
        
        # 执行命令
        if eval $ossutil_cmd 2>/dev/null; then
            log "✓ OSS连接测试成功"
            rm -f "$test_file"
            return 0
        else
            error "OSS连接测试失败"
            rm -f "$test_file"
            return 1
        fi
    else
        warn "ossutil未安装，跳过详细连接测试"
        log "配置信息看起来格式正确"
        rm -f "$test_file"
        return 0
    fi
}

# 显示配置信息（隐藏敏感信息）
show_oss_config() {
    if [ ! -f "$CONFIG_FILE" ]; then
        error "OSS配置文件不存在"
        return 1
    fi
    
    log "OSS配置信息:"
    echo "=========================================="
    grep -v -E "(ACCESS_KEY_SECRET|SECURITY_TOKEN)" "$CONFIG_FILE" | \
    sed 's/your-access-key-id/********/' | \
    sed 's/your-access-key-secret/********/'
    echo "=========================================="
}

# 安装ossutil工具
install_ossutil() {
    log "安装ossutil工具..."
    
    local ossutil_url="http://gosspublic.alicdn.com/ossutil/1.7.18/ossutil64"
    local install_path="/usr/local/bin/ossutil"
    
    if command -v ossutil &> /dev/null; then
        log "✓ ossutil 已安装: $(ossutil version)"
        return 0
    fi
    
    if wget -O "$install_path" "$ossutil_url"; then
        chmod +x "$install_path"
        log "✓ ossutil 安装成功"
        return 0
    else
        error "ossutil 安装失败"
        return 1
    fi
}


# 显示使用说明
show_usage() {
    echo "OSS配置管理工具"
    echo ""
    echo "用法: $0 {init|edit|validate|test|show|install|help}"
    echo ""
    echo "命令:"
    echo "  init      - 初始化OSS配置文件"
    echo "  edit      - 编辑OSS配置"
    echo "  validate  - 验证配置格式"
    echo "  test      - 测试OSS连接"
    echo "  show      - 显示配置信息"
    echo "  install   - 安装ossutil工具"
    echo "  help      - 显示此帮助"
    echo ""
    echo "示例:"
    echo "  $0 init      # 首次使用"
    echo "  $0 edit      # 配置AccessKey"
    echo "  $0 test      # 测试连接"
}

case "$1" in
    "init")
        init_oss_config
        ;;
    "edit")
        edit_oss_config
        ;;
    "validate")
        validate_oss_config
        ;;
    "test")
        test_oss_connection
        ;;
    "show")
        show_oss_config
        ;;
    "install")
        install_ossutil
        ;;
    "help"|"--help"|"-h")
        show_usage
        ;;
    *)
        show_usage
        exit 1
        ;;
esac